package user.service.impl;

import blog.api.BlogServiceAPI;
import blog.api.pojo.BlogInfoResponse;
import blog.common.exception.BlogException;
import blog.common.pojo.Result;
import blog.common.utils.*;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import jakarta.validation.constraints.NotBlank;
import lombok.extern.slf4j.Slf4j;
import org.hibernate.validator.constraints.Length;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestBody;
import user.api.pojo.*;
import user.common.dataobject.UserInfo;
import user.convert.BeanConvert;
import user.mapper.UserInfoMapper;
import user.service.UserService;

import java.util.HashMap;
import java.util.Map;


@Slf4j
@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserInfoMapper userInfoMapper;

    @Autowired
    private BlogServiceAPI blogService;

    @Autowired
    private Redis redis;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    private static final String USER_PRFIX = "user";

    private static final long TIME_OUT = 60 * 60 * 24 * 7;

    @Override
    public UserLoginResponse login(UserInfoRequest user) {
        //验证账号密码是否正确
        UserInfo userInfo = queryUserInfo(user.getUserName());
        if (userInfo==null || userInfo.getId()==null){
            throw new BlogException("用户不存在");
        }
//        if (!user.getPassword().equals(userInfo.getPassword())){
//            throw new BlogException("用户密码不正确");
//        }
        if (!SecurityUtil.verify(user.getPassword(),userInfo.getPassword())){
            throw new BlogException("用户密码不正确");
        }
        //账号密码正确的逻辑
        Map<String,Object> claims = new HashMap<>();
        claims.put("id", userInfo.getId());
        claims.put("name", userInfo.getUserName());

        String jwt = JWTUtils.genJwt(claims);
        return new UserLoginResponse(userInfo.getId(), jwt);
    }



    @Override
    public UserInfoResponse getUserInfo(Integer userId) {
        UserInfoResponse userInfoResponse = new UserInfoResponse();
        UserInfo userInfo = selectUserInfoById(userId);
        BeanUtils.copyProperties(userInfo, userInfoResponse);
        return userInfoResponse;
    }

    @Override
    public UserInfoResponse selectAuthorInfoByBlogId(Integer blogId) {
        UserInfoResponse userInfoResponse = new UserInfoResponse();
        //1. 根据博客ID, 获取作者ID
        Result<BlogInfoResponse> blogDetail = blogService.getBlogDeatail(blogId);
        //2. 根据作者ID, 获取作者信息
        if (blogDetail == null || blogDetail.getData() == null){
            throw new BlogException("博客不存在");
        }
        UserInfo userInfo = selectUserInfoById(blogDetail.getData().getUserId());
        BeanUtils.copyProperties(userInfo, userInfoResponse);
        return userInfoResponse;
    }

    @Override
    public Integer register(@Validated @RequestBody UserInfoRegisterRequest userInfoRegister) {
        //检查用户名是否存在，邮箱格式是否正确
        checkRegisterInfo(userInfoRegister);
        UserInfo userInfo = BeanConvert.convertUserInfoEncrypt(userInfoRegister);
        try {
            Integer result = userInfoMapper.insert(userInfo);
            if (result == 1){
                redis.set(bulidKey(userInfo.getUserName()),JsonUtil.toJson(userInfo),TIME_OUT);
                userInfo.setPassword("");
                rabbitTemplate.convertAndSend("user.exchange","",JsonUtil.toJson(userInfo));
                return userInfo.getId();
            }else {
                throw new BlogException("用户注册失败！");
            }
        }catch (Exception e){
            log.info("用户注册失败: {}",e.getMessage());
            throw new BlogException("用户注册失败！");
        }
    }

    private String bulidKey(String userName) {
        return redis.bulidKey(USER_PRFIX,userName);
    }

    private void checkRegisterInfo(UserInfoRegisterRequest userInfoRegister) {
        //用户名不能重复
       UserInfo userInfo = selectUserInfoByName(userInfoRegister.getUserName());
       if (userInfo != null) {
           throw new BlogException("用户名已经存在");
       }
       //邮箱和Url格式校验
        if (!RegexUtil.checkMail(userInfoRegister.getEmail())) {
            throw new BlogException("邮箱不合法");
        }

        if (!RegexUtil.checkURL(userInfoRegister.getGithubUrl())) {
            throw new BlogException("github地址不合法");
        }
    }


    private UserInfo queryUserInfo(String userName) {
        String key = bulidKey(userName);
        boolean exit = redis.hasKey(key);
        if (exit) {
            log.info("redis获取");
            UserInfo userInfo = JsonUtil.parse(redis.get(key),UserInfo.class);
           return userInfo == null ? selectUserInfoByName(userName) : userInfo;
        }else {
            log.info("mysql中获取");
            UserInfo userInfo = selectUserInfoByName(userName);
            redis.set(key,JsonUtil.toJson(userInfo),TIME_OUT);
            return userInfo;
        }
    }


    public UserInfo selectUserInfoByName(String userName) {
        return userInfoMapper.selectOne(new LambdaQueryWrapper<UserInfo>()
                .eq(UserInfo::getUserName, userName).eq(UserInfo::getDeleteFlag, 0));
    }
    private UserInfo selectUserInfoById(Integer userId) {
        return userInfoMapper.selectOne(new LambdaQueryWrapper<UserInfo>()
                .eq(UserInfo::getId, userId).eq(UserInfo::getDeleteFlag, 0));
    }
}
